package com.framework.component.resolver.register;

import com.framework.component.resolver.Resolver;
import com.framework.component.resolver.ValueResolver;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;

import java.util.Map;

@Component
public class ResolverExecutor {

    private final ResolverRepository resolverRepository;

    public ResolverExecutor(ResolverRepository resolverRepository) {
        this.resolverRepository = resolverRepository;
    }

    public void execute(Object context) {
        ReflectionUtils.doWithFields(context.getClass(), field -> {
            Resolver resolverAnnotation = AnnotationUtils.getAnnotation(field, Resolver.class);
            if (resolverAnnotation == null) {
                return;
            }

            Class<?> resolverKey = resolverAnnotation.value();
            if (!getResolverRepos().containsKey(resolverKey)) {
                return;
            }

            ValueResolver valueResolver = getResolverRepos().get(resolverKey);
            Object result = valueResolver.resolve(context);
            ReflectionUtils.makeAccessible(field);
            ReflectionUtils.setField(field, context, result);
        });
    }

    private Map<Class<?>, ValueResolver<?, ?>> getResolverRepos() {
        return resolverRepository.getResolverRepos();
    }
}
